package com.xiaoshu.user.controller;

import com.xiaoshu.common.Result;
import com.xiaoshu.common.ResultGenerator;
import com.xiaoshu.interceptor.ClientAuthorization;
import com.xiaoshu.user.entity.TUser;
import com.xiaoshu.user.service.ITUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 * http://127.0.0.1:8080/v1/score-server/user/t-user/10001
 * 此处集成了SpringCache， 同一个userid, 第一次请求会缓存，后面在请求，则直接走缓存；
 *
 * @author deane
 * @since 2021-06-16
 */
@RestController
@RequestMapping("/user/t-user")
@Slf4j
@Api(value = "用户管理")
public class TUserController {

    private ITUserService userService;

    @Autowired
    public void setUserService(ITUserService userService) {
        this.userService = userService;
    }

    @GetMapping(value = "/{userId}")
    @ApiOperation(value = "根据id获取到用户信息")
    @ClientAuthorization
    public Result getUserById(@ApiParam(value = "userId") @PathVariable String userId) {
        log.info("[GetUserById] get user by Id :{}", userId);
        TUser user = userService.getUserByUserId(userId);
        return ResultGenerator.success(user);
    }

    @PutMapping(value = "/{userId}")
    @ApiOperation(value = "更新用户信息")
    public Result updateUserByUserId(@ApiParam(value = "userId") @PathVariable String userId,
                                     @ApiParam(value = "user") @RequestBody TUser user) {
        log.info("[UpdateUserByUserId] update User By userId :{}", userId);
        userService.updateUserByUserId(userId, user);
        return ResultGenerator.success(user);
    }

    @DeleteMapping(value = "/{userId}")
    @ApiOperation(value = "删除用户信息")
    public Result deleteUserByUserId(@ApiParam(value = "userId") @PathVariable String userId) {
        log.info("[DeleteUserByUserId] update User By userId :{}", userId);
        userService.deleteUserByUserId(userId);
        return ResultGenerator.success();
    }

    @PostMapping(value = "/")
    @ApiOperation(value = "保存用户信息")
    public Result saveUserInfo(@ApiParam(value = "user")  @RequestBody TUser user) {
        TUser newUser = userService.saveUser(user);
        return ResultGenerator.success(newUser);
    }

}
